package com.bookseek.xreader.service.dk;

import android.database.Cursor;

import com.bookseek.xreader.consts.XreaderConts;
import com.bookseek.xreader.dao.TMetaPoDao;
import com.bookseek.xreader.dbhelper.DbSessionUtils;
import com.bookseek.xreader.po.TMetaPo;
import com.bookseek.xreader.utils.DLog;
import com.bookseek.xreader.utils.JkhlUtils;
import com.bookseek.xreader.vo.MiniBaseInfoVo;

import org.greenrobot.greendao.database.Database;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class TMetaService {
    private static  TMetaService instance;

    private static TMetaPoDao tMetaPoDao;

    private TMetaService(){}


    public static TMetaService getInstance(){
        if(instance == null){
            synchronized (TMetaService.class){
                if(instance == null){
                    instance = new TMetaService();
                    tMetaPoDao =  DbSessionUtils.genDaoSession().getTMetaPoDao();
                }
            }
        }
        return instance;
    }



    public TMetaPo updateSelectiveById(TMetaPo up){
        if(up.id ==  null){
            return up;
        }

        List<Object> args = new ArrayList<>();
        List<String> pres = new ArrayList<>();
        if(up.dflag != null){
            pres.add(" dflag = ? ");
            args.add(up.dflag);
        }
        if(up.bmin != null){
           pres.add(" bmin = ? ");
           args.add(up.bmin);
        }
        if(up.bmax != null){
            pres.add(" bmax = ? ");
            args.add(up.bmax);
        }
        if(up.bcount != null){
            pres.add(" bcount = ? ");
            args.add(up.bcount);
        }
        if(up.bids != null){
            pres.add(" bids = ? ");
            args.add(up.bids);
        }
        if(up.bkey != null){
            pres.add(" bkey = ? ");
            args.add(up.bkey);
        }
        if(!pres.isEmpty()){
            DLog.info("update TMeta id=",up.id,"plat=",up.plat,"dflag=",up.dflag,"bmin=",up.bmin,"bmax=",up.bmax,"bcount=",up.bcount);
            StringBuffer sql = new StringBuffer(" UPDATE ").append(TMetaPoDao.TABLENAME).append(" SET ");
            sql.append(String.join(",",pres)).append(" WHERE id = ? ");
            args.add(up.id);
            Database db = tMetaPoDao.getDatabase();
            db.execSQL(sql.toString(),args.toArray());
        }
        return up;
    }

    public Set<String> getExistBsigns(Set<String> bsigns){
        Set<String> dbsigns = new HashSet<>();
        if(bsigns == null || bsigns.isEmpty()){
            return dbsigns;
        }
        Database db = tMetaPoDao.getDatabase();
        String bsignColName = TMetaPoDao.Properties.Bsign.columnName;
        String sql = "select "+bsignColName+" from "+TMetaPoDao.TABLENAME+ " where "+bsignColName+" in ("+bsigns.stream().map(d->"'"+d+"'").collect(Collectors.joining(","))+")";
        Cursor cursor = db.rawQuery(sql, null);
        try{
            // 遍历 Cursor 处理结果
            if (cursor.moveToFirst()) {
                do {
                    String bsign = cursor.getString(cursor.getColumnIndexOrThrow(bsignColName));
                    dbsigns.add(bsign);
                    // 处理数据...
                } while (cursor.moveToNext());
            }
        }finally {
            if(cursor != null && !cursor.isClosed()){
                DLog.info("getExistBsigns 关闭 cursor ");
                cursor.close();
            }
        }

        return dbsigns;
    }
    public void saveTMetaInfo(MiniBaseInfoVo infoVo){
        if(infoVo == null){
            DLog.error("MiniBaseInfoVo is null");
            return;
        }
        List<TMetaPo> metas = infoVo.metas;
        Set<String> bsigns = metas.stream().map(d->d.bsign).collect(Collectors.toSet());
        Set<String> dbSigns = getExistBsigns(bsigns);
        DLog.info("TMeta db bsigns size is ",dbSigns.size());
        List<TMetaPo> addPos = metas.stream().filter(d->!dbSigns.contains(d.bsign)).collect(Collectors.toList());
        for(TMetaPo po : addPos){
            if(JkhlUtils.isBlank(po.bkey) && JkhlUtils.notBlank(po.filename)){
                //提取前缀名
                String[] strs = JkhlUtils.toStr(po.filename).split("[.]");
                po.bkey = strs.length > 0 ? strs[0] : po.filename;
            }
        }
        DLog.info("TMeta add size is ",addPos.size());
        if(addPos.size() > 0){
            tMetaPoDao.insertInTx(addPos);
        }
    }

    public List<TMetaPo> getByBtype(Integer btype){
        List<TMetaPo> datas = tMetaPoDao.queryBuilder()
                .where(TMetaPoDao.Properties.Btype.eq(btype))
                .list();
        return datas;
    }

    public Map<String, List<TMetaPo>> getDownMetaMapByBtype(Integer btype){
        Map<String,List<TMetaPo>> dataMap = new HashMap<>();
        List<TMetaPo> datas = getByBtype(btype);
        for(TMetaPo po : datas){
            String bkey = po.bkey;
            dataMap.computeIfAbsent(bkey,k->new ArrayList<>()).add(po);
        }
        return dataMap;
    }

    public List<TMetaPo> getShiciMeta(){
        return getByBtype(XreaderConts.TMETA_BTYPE_SHICI);
    }

    public Map<String, List<TMetaPo>> getShiciDownMetaMap(){
        Map<String,List<TMetaPo>> dataMap = new HashMap<>();
        List<TMetaPo> datas = getShiciMeta();
        for(TMetaPo po : datas){
            String bkey = po.bkey;
            dataMap.computeIfAbsent(bkey,k->new ArrayList<>()).add(po);
        }
        return dataMap;
    }
}
